package com.ssi.myshop.Presenter.impl;

import android.util.Log;

import com.ssi.myshop.Presenter.ILoginPresenter;
import com.ssi.myshop.base.BaseData;
import com.ssi.myshop.base.BaseObserver;
import com.ssi.myshop.bean.LoginBean;
import com.ssi.myshop.contants.Api;
import com.ssi.myshop.utils.RetrofitManager;
import com.ssi.myshop.utils.RxUtil;
import com.ssi.myshop.view.ILoginCallBack;

import java.util.HashMap;

import io.reactivex.Observable;
import retrofit2.Retrofit;

public class ILoginPresenterImpl implements ILoginPresenter {
    private static final String TAG = "ILoginPresenterImpl";

    private ILoginCallBack mCallBack;
    private Retrofit retrofit;

    @Override
    public void doLogin(String name, String pwd) {
        retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        HashMap<String, Object> params = new HashMap<>();
        params.put("deviceName","1");//登录设备ID，自定义即可
        params.put("deviceId","1");//登录设备ID，自定义即可
        params.put("username",name);//用户名
        params.put("pwd",pwd);//登录密码
//        OkHttpClient okHttpClient = new OkHttpClient();
//        FormBody formBody = new FormBody.Builder()
//                .add("deviceName", "1")
////                .add("deviceId", "1")
//                .add("username", "1")
//                .add("pwd", "1")
//                .build();
//        Request request = new Request.Builder()
//                .url("https://api.it120.cc/tristan/user/username/login")
//                .post(formBody)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: "+e.toString());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                Log.d(TAG, "onResponse: "+response.body().string());
//            }
//        });

        Observable<BaseData<LoginBean>> observable = api.login(params);
        observable.compose(RxUtil.schedulerTransformer())
                .subscribeWith(new BaseObserver<LoginBean>(mCallBack) {
                    @Override
                    protected void onSuccess(LoginBean data) {
                        Log.d(TAG, "onSuccess: "+data.toString());
                        if (data != null) {
                            mCallBack.onLoginSuccess(data);
                        }
                    }
                });
    }

    @Override
    public void registerViewCallBack(ILoginCallBack callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void unregisterViewCallBack(ILoginCallBack callBack) {
        if (mCallBack != null) {
            mCallBack = null;
        }
    }
}
